<template>
  <el-tree
    ref="tree" 
    :data="list" :props="{label:'name'}"
    default-expand-all
    :show-checkbox="true"
    :check-strictly="true"
    node-key="id"
  />
  <el-row type="flex" justify="center">
    <el-button type="primary" @click="onSubmit"> 确认</el-button>
    <el-button @click="emit('close')">取消</el-button>
  </el-row>
</template>
  
<script setup lang="ts">
import { getRoleDetail ,assignPerm } from '@/api/settings'
import { getPermissionList  } from '@/api/permissions'
import { transTreeData } from '@/utils/transTreeData'
const list =ref<TreeObj[]>()
const loadPermissionList =async() => {
  try {
    const res = await getPermissionList()
    console.log('getPermissionList',res)
    list.value=transTreeData(res.data)
  } catch (error) {
    console.log(error)
  }
}
loadPermissionList()
const props= defineProps<{
      id:string
  }>()
const emit=defineEmits(['close','success'])
//选中权限
const tree=ref()
const loadProfileById =async() => {
  try {
    const res = await getRoleDetail(props.id)
    console.log('getRoleDetail',res)
    // 回填
    tree.value!.setCheckedKeys(res.data.permIds, false)
  } catch (error) {
    console.log(error)
  }
}
loadProfileById()
//修改权限
const loadAssignRoles =async() => {
  try {
    const permIds=tree.value!.getCheckedKeys(false)
    const res = await assignPerm({ id:props.id ,permIds })
    console.log('assignPerm',res)
    emit('success')
    loadPermissionList()
  } catch (error) {
    console.log(error)
  }
}
const onSubmit=() => {
  loadAssignRoles()
}

defineExpose({ loadProfileById })
</script>